package com.jmodata.zxu.interceptor;

import com.jmodata.zxu.pojo.manager.Manager;
import com.jmodata.zxu.utils.StringOrDate.XhrtStringUtils;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class SessionInterceptor implements HandlerInterceptor {

	private Logger logger = Logger.getLogger(SessionInterceptor.class);


	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

		String url = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/"));

		String menuId = request.getParameter("menuId");
		if (!XhrtStringUtils.isEmpty(menuId)) {
			request.setAttribute("menuId", menuId);
		}

		if (url.equals("/loginout") || url.equals("/managerLogin") || url.contains("/phone")) {
			return true;
		} else {
			Manager manager = (Manager) request.getSession().getAttribute("mgr");
//			Shop shopMgr = (Shop) request.getSession().getAttribute("shopMgr");
			// 如果没有登录，则跳转到登录页面
			if (manager == null) {
				logger.info("没有登录");
				PrintWriter out = response.getWriter();
				String login_url = "manager/loginout";
				out.println("<html>");
				out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /><script>");
				out.println("alert('会话已过期，请重新登陆！');");
				out.println("top.window.location.href='" + login_url + "';");
				out.println("</script>");
				out.println("</html>");
				return false;
			} else {
				return true;
			}
		}
	}

	// private boolean checkTime() {
	// Date dt = new Date();
	// SimpleDateFormat sd = new SimpleDateFormat(XhrtDateUtils.DATE_FORMATE_YYYYMMDD);
	// String nowDate = sd.format(dt);
	// int checkCount = XhrtDateUtils.compareDate(nowDate, CommonContant.USER_DATE,
	// XhrtDateUtils.DATE_FORMATE_YYYYMMDD);
	// if (checkCount > 0) {
	// return false;
	// }
	// return true;
	// }

}
